package com.wy.component.dataConvert;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.lang3.StringUtils;

public class DateUtil {

	private final static String regex_full_time = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}";
	
	private final static SimpleDateFormat sdf_full_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
	
    private final static String regex_time = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}";

    private final static SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm" );

    private final static String regex_date = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}";
    
    private final static SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd" );
    
	private static final String SHORT_DATE = "yyyy-MM-dd";
	private static final String SHORTDATE = "yyyyMMdd";
	private static final String LONG_DATE = "yyyy-MM-dd HH:mm:ss";
	private static final String LONGDATE = "yyyyMMddHHmmss";
	private static final String TIME = "HH:mm:ss";
    // three comman date format
	public static final SimpleDateFormat longFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat dashFormat = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat slashForamt = new SimpleDateFormat("yyyy/MM/dd");
    public static final SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyyMMdd");
    public static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
    public static final long M_PER_DAY = 1000 * 60 * 60 * 24;

	public static boolean isNull(String str) {
		if (str==null||str.equals(""))
			return true;
		return false;
	}
	
	static public Date convertToDate( String value, String format ) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (!isNull(value)) {
			try {
				return sdf.parse( value );
			}catch (Exception e) {
				System.err.println("Exception caught: " + e.getMessage());
			}
		}
		return null;
	}
	
	public static Date convertToDate(String value) throws ParseException {
		if (value.matches(regex_full_time))
			return sdf_full_time.parse(value);
		if (value.matches(regex_time))
			return sdf_time.parse(value);
		else if (value.matches(regex_date))
			return sdf_date.parse(value);

		return null;
	}
	
	static public long getDayOfWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
	    return c.get(Calendar.DAY_OF_WEEK);
	}
	
	// 得到指定年月的最后一天
	public static Date getLastDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
	    c.add(Calendar.MONTH, 1);//本月最后一天
	    c.set(Calendar.DAY_OF_MONTH, 1);
	    c.add(Calendar.DAY_OF_MONTH, -1);
	    return c.getTime();
	
	}
	
	 public static Date getFirstDate(Date date) {
			Calendar cld = Calendar.getInstance();
			cld.setTime(date);
			cld.set(Calendar.DAY_OF_MONTH, 1);//本月第一天
			cld.set(Calendar.HOUR_OF_DAY, 0);
			cld.set(Calendar.MINUTE, 0);
			cld.set(Calendar.SECOND, 0);
			return cld.getTime();
	}
	 
	// 得到指定年月日   当天第一秒
	public static Date getFirstSecond(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
	    return c.getTime();
	
	}
	
	// 得到指定年月日   当天最后一秒
	 public static Date getLastSecond(Date date) {
			Calendar cld = Calendar.getInstance();
			cld.setTime(date);
			cld.set(Calendar.HOUR_OF_DAY, 23);
			cld.set(Calendar.MINUTE, 59);
			cld.set(Calendar.SECOND, 59);
			return cld.getTime();
	}
	
	 public static Date getDiffDate(Date date, int diff) {
		Calendar cld = Calendar.getInstance();
		cld.setTime(date);
		cld.add(Calendar.DATE, diff);
		return cld.getTime();
	}
	
	// 获得两日期间隔的天数
	public static long getBetweenDays(Date d1, Date d2) {
		long betweenDays = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d1);
		c2.setTime(d2);
		// 保证第二个时间一定大于第一个时间
		if (c1.after(c2)) {
			c1 = c2;
			c2.setTime(d1);
		}
		int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
		betweenDays = c2.get(Calendar.DAY_OF_YEAR)
				- c1.get(Calendar.DAY_OF_YEAR);
		for (int i = 0; i < betweenYears; i++) {
			c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
			betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
		}
		return betweenDays;
	}

    public static String getDateString(Date date, DateFormat format) {
        return format.format(date);
    }

    public static String getDateString(Date date, String formatString) {
        return new SimpleDateFormat(formatString).format(date);
    }

    /**
     * use the default date format "yyyy-MM-dd"
     *
     * @param dStr
     * @return
     */
    public static Date getDate(String dStr) {
        return getDate(dStr, dashFormat);
    }

    public static Date getDate(String dStr, DateFormat format) {
        format.setLenient(false);
        Date date = null;
        try {
            date = format.parse(dStr);
        } catch (ParseException ex) {
            ex.getStackTrace();
        }
        return date;
    }

    public static Date getDate(String dStr, String formatString) {
        SimpleDateFormat format = new SimpleDateFormat(formatString);
        return getDate(dStr, format);
    }

    /**
     * assume: 1. endDate should be after beginDate 2. if endDate is 2/29,
     * return true 2. endDate - beginDate can be > 1Y 3. if endDate - beginDate >
     * 1Y, find between beginDate and (endDate-xY), x: the largest number that
     * (endDate-xY) is after beginDate 3. 算头不算尾
     *
     * @param beginDate
     * @param end
     * @return
     */
    public static boolean hasLeapDayInBetween(GregorianCalendar beginDate, Date end) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        GregorianCalendar endDate = new GregorianCalendar();
        endDate.setTime(end);

        if (beginDate.before(endDate) == false) // illegal setting: endDate
        // should be after beginDate
        {
            return false;
        }

        if (endDate.get(Calendar.MONTH) == Calendar.FEBRUARY && endDate.get(Calendar.DATE) == 29) {
            return true; // endDate is 2/29
        }

        // find (paymentDate-xY), x: the largest number that (paymentDate-xY) is
        // after valueDate
        GregorianCalendar newEndDate = new GregorianCalendar(beginDate.get(Calendar.YEAR), endDate.get(Calendar.MONTH), endDate.get(Calendar.DATE));

        if (newEndDate.after(beginDate) == false) {
            newEndDate = new GregorianCalendar(newEndDate.get(Calendar.YEAR) + 1, newEndDate.get(Calendar.MONTH), newEndDate.get(Calendar.DATE));
        }

        endDate = new GregorianCalendar(newEndDate.get(Calendar.YEAR), newEndDate.get(Calendar.MONTH), newEndDate.get(Calendar.DATE));

        int leapYearIdx = beginDate.get(Calendar.YEAR);
        if (beginDate.isLeapYear(leapYearIdx) == true) // valueDate is in a
        // leap year
        {
            GregorianCalendar cal229 = new GregorianCalendar(leapYearIdx, Calendar.FEBRUARY, 29);

            if (beginDate.after(cal229) == false) // valueDate is at 2/29 or
            // before in a leap year
            {
                if (endDate.after(cal229) == true) // check endDate
                {
                    return true;
                } else {
                    return false;
                }
            } else // beginDate is after 2/29
            {
                return false;
            }
        }

        leapYearIdx += 1; // check next year
        if (beginDate.isLeapYear(leapYearIdx) == true) // the next year is a
        // leap year
        {
            GregorianCalendar next229 = new GregorianCalendar(leapYearIdx, Calendar.FEBRUARY, 29);

            if (endDate.after(next229) == true) // check paymentDate
            {
                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    public static boolean hasLeapDayInBetween(Date calDate, Date paymentDate) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(calDate);
        return hasLeapDayInBetween(cal, paymentDate);
    }

    public static int getDaysBetween(String date1, String date2) {
        return DateUtil.getDaysBetween(DateUtil.getDate(date1), DateUtil.getDate(date2));
    }

    public static int getDaysBetween(Date preDate, Date nextDate) {
        return (int) ((nextDate.getTime() - preDate.getTime()) / M_PER_DAY);
    }

    /**
     * 假设每月30天的条件下计算两天之相隔天数
     */
    public static int getDaysBetween(Date preDate, Date nextDate, int daysPerYear) {
        GregorianCalendar pre = new GregorianCalendar();
        pre.setTime(preDate);
        GregorianCalendar next = new GregorianCalendar();
        next.setTime(nextDate);
        return (next.get(Calendar.YEAR) - pre.get(Calendar.YEAR)) * daysPerYear
                + (next.get(Calendar.MONTH) - pre.get(Calendar.MONTH)) * 30 + (next.get(Calendar.DATE) - pre.get(Calendar.DATE));

    }

    /**
     * 取得两日间的整年数 1. preDate cannot be after nextDate. if so, return -1
     *
     * @param preDate
     * @param nextDate
     * @return
     */
    public static int getYearsBetween(Date preDate, Date nextDate) {
        if (preDate.after(nextDate) == true) {
            return -1;
        }
        GregorianCalendar valueDate = new GregorianCalendar();
        valueDate.setTime(preDate);
        GregorianCalendar oldNextDate = new GregorianCalendar();
        oldNextDate.setTime(nextDate);

        GregorianCalendar newNextDate = new GregorianCalendar(valueDate.get(Calendar.YEAR), oldNextDate.get(Calendar.MONTH),
                oldNextDate.get(Calendar.DATE));
        // 考虑相等的情况
        if (newNextDate.before(valueDate)) {
            newNextDate = new GregorianCalendar(newNextDate.get(Calendar.YEAR) + 1, newNextDate.get(Calendar.MONTH), newNextDate.get(Calendar.DATE));
        }

        return oldNextDate.get(Calendar.YEAR) - newNextDate.get(Calendar.YEAR);
    }

    /**
     * 得到年限，格式为XX年XX月XX日
     *
     * @param next
     * @param pre
     * @return
     */
    public static int[] getTimeYear(Date pre, Date next) {

        GregorianCalendar preDate = new GregorianCalendar();
        preDate.setTime(pre);
        GregorianCalendar nextDate = new GregorianCalendar();
        nextDate.setTime(next);

        boolean isLeap = nextDate.isLeapYear(nextDate.get(Calendar.YEAR));
        int year = nextDate.get(Calendar.YEAR) - preDate.get(Calendar.YEAR);
        int month = nextDate.get(Calendar.MONTH) - preDate.get(Calendar.MONTH);
        int day;
        if (isSecondMonthMaxDay(nextDate, preDate)) {
            day = 0;
        } else {
            day = nextDate.get(Calendar.DAY_OF_MONTH) - preDate.get(Calendar.DAY_OF_MONTH);
        }

        if (day < 0) {
            nextDate.add(Calendar.MONTH, -1);
            int lastMonth = nextDate.get(Calendar.MONTH);
            day = day + getDay_Month(isLeap, lastMonth);
            month = nextDate.get(Calendar.MONTH) - preDate.get(Calendar.MONTH);
            year = nextDate.get(Calendar.YEAR) - preDate.get(Calendar.YEAR);
        }
        if (month < 0) {
            nextDate.add(Calendar.YEAR, -1);
            month = month + 12;
            year = nextDate.get(Calendar.YEAR) - preDate.get(Calendar.YEAR);
        }

        int[] storeDate = new int[3];
        storeDate[0] = year;
        storeDate[1] = month;
        storeDate[2] = day;
        return storeDate;
    }

    public static boolean isSecondMonthMaxDay(GregorianCalendar next, GregorianCalendar pre) {
        if (next.get(Calendar.MONTH) == 1 && pre.get(Calendar.MONTH) == 1) {
            boolean isLeap1 = next.isLeapYear(next.get(Calendar.YEAR));
            boolean isLeap2 = pre.isLeapYear(pre.get(Calendar.YEAR));
            int next_DayOfMonth = getDay_Month(isLeap1, next.get(Calendar.MONTH));
            int pre_DayOfMonth = getDay_Month(isLeap2, pre.get(Calendar.MONTH));

            if (next.get(Calendar.DAY_OF_MONTH) == next_DayOfMonth
                    && pre.get(Calendar.DAY_OF_MONTH) == pre_DayOfMonth) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 根据月份得到该月的天数（月是以0开始）
     */
    public static int getDay_Month(boolean isLeap, int month) {
        if (month == 0) {
            return 31;
        }
        if (month == 1) {
            if (isLeap) {
                return 29;
            } else {
                return 28;
            }
        }
        if (month == 2) {
            return 31;
        }
        if (month == 3) {
            return 30;
        }
        if (month == 4) {
            return 31;
        }
        if (month == 5) {
            return 30;
        }
        if (month == 6) {
            return 31;
        }
        if (month == 7) {
            return 31;
        }
        if (month == 8) {
            return 30;
        }
        if (month == 9) {
            return 31;
        }
        if (month == 10) {
            return 30;
        }
        if (month == 11) {
            return 31;
        }
        return -1;
    }

    /**
     * format the date to be only yyyyMMdd
     *
     * @param date
     * @return
     */
    public static Date getFormattedDate(Date date) {
        GregorianCalendar gday = new GregorianCalendar();
        gday.setTime(date);
        gday.set(Calendar.HOUR, 0);
        gday.set(Calendar.HOUR_OF_DAY, 0);
        gday.set(Calendar.MINUTE, 0);
        gday.set(Calendar.SECOND, 0);
        gday.set(Calendar.MILLISECOND, 0);

        date = gday.getTime();
        return date;
    }

    /**
     * clean the cal to only yyyyMMdd
     *
     * @param cal
     * @return
     */
    public static GregorianCalendar getCleanCalendar(GregorianCalendar cal) {
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        return cal;
    }

    /**
     * convent method to get days after or before
     *
     * @param date
     * @param days
     * @return
     */
    public static Date getDateAfter(Date date, int days) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    /**
     * convent method to get days after or before
     *
     * @param date
     * @param days
     * @param field
     * @return
     */
    public static Date getDateAfter(Date date, int field, int days) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(field, days);
        return calendar.getTime();
    }

    /**
     * convent method to get days after or before
     *
     * @param date
     * @param year
     * @param month
     * @param days
     * @return
     */
    public static Date getDateAfter(Date date, int year, int month, int days) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        calendar.add(Calendar.MONTH, month);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    public static Date getDateAfterMonth(Date date, int month) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        boolean is229 = false;
        if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY && calendar.get(Calendar.DATE) == 29) {
            is229 = true; // calendar is 2/29
        }

        int oldMonthIdx = calendar.get(Calendar.MONTH);

        calendar.add(Calendar.YEAR, month / 12);
        calendar.roll(Calendar.MONTH, month % 12);

        if (is229 == true) {
            if (calendar.isLeapYear(calendar.get(Calendar.YEAR)) == false
                    && calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                calendar.set(Calendar.DATE, 28);
            } else {
                calendar.set(Calendar.DATE, 29);
            }
        }

        int newMonthIdx = calendar.get(Calendar.MONTH);

        if (month > 0 && oldMonthIdx > newMonthIdx) {
            calendar.add(Calendar.YEAR, 1);
        } else if (month < 0 && oldMonthIdx < newMonthIdx) {
            calendar.add(Calendar.YEAR, -1);
        }

        return calendar.getTime();
    }

    public static Date getDateAfterYear(Date date, int year) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        return calendar.getTime();
    }

    /**
     * convent method to get year for date
     *
     * @param date
     * @return
     */
    public static int getYearForDate(Date date) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 得到月份，calendar从 0 计数，所以需加一，才为实际所称月
     *
     * @param date
     * @return
     */
    public static int getMonthForDate(Date date) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static int getDayForDate(Date date) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    /**
     * = 计算剩余期限 2007/09/06 change to A/A 2.29要计算
     *
     * @param valueDate
     * @param maturityDate
     * @return
     */
    public static double getLastYear(Date prevCpnDate, Date valueDate, Date maturityDate, int dayCount, boolean count229) {
        int years = getYearsBetween(valueDate, maturityDate);

        if (years < 0) {
            return 0; // valueDate is after bond maturityDate
        }
        GregorianCalendar latestMat = new GregorianCalendar();
        latestMat.setTime(maturityDate);
        latestMat.set(Calendar.YEAR, latestMat.get(Calendar.YEAR) - years);
        Date latestMatDate = latestMat.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        if (sdf.format(valueDate).equals(sdf.format(latestMatDate))) {
            return years;
        }

        int interDays = DateUtil.getDaysBetween(valueDate, latestMatDate);
        if (dayCount == 2 && count229 == false) {
            DateUtil.getDaysBetweenWithoutLeapYear(valueDate, latestMatDate);
        }

        double daysInYear = getDayCountOfYear(prevCpnDate, valueDate);
        if (dayCount == 2) {
            daysInYear = 365;
        }

        return years + (interDays / daysInYear);
    }

    public static boolean checkDateValidity(String str,String formatString){
      SimpleDateFormat sdf = new SimpleDateFormat(formatString);
        sdf.setLenient(false);
        try {
          sdf.parse(str);
          return true;
        } catch (ParseException e) {
          return false;
        }
    }
    
    /**
     * 提供方便进行date格式转换的方法
     *
     * @param source
     * @param srcFormat
     * @param desFormat
     * @return
     */
    public static String convertDate(String source, String srcFormat, String desFormat) {
        Date date = getDate(source, srcFormat);
        if (date == null) {
            return source;
        }

        return getDateString(date, desFormat);
    }

    /**
     * 提供方便进行date格式转换的方法
     *
     * @param source
     * @param srcFormat
     * @param desFormat
     * @return
     */
    public static String convertDate(String source, DateFormat srcFormat, DateFormat desFormat) {
        Date date = getDate(source, srcFormat);
        if (date == null) {
            return source;
        }

        return getDateString(date, desFormat);
    }

    /**
     * = 取得该付息区间应使用的一年天数
     *
     * @return
     */
    public static double getDayCountOfYear(Date prevCouponDate, Date valueDate) {

        GregorianCalendar prevDate = new GregorianCalendar();
        prevDate.setTime(prevCouponDate);

        if (prevDate.get(Calendar.MONTH) == Calendar.FEBRUARY && prevDate.get(Calendar.DATE) == 29) {
            return 365.0; // date is 2/29
        }

        GregorianCalendar nextDate = new GregorianCalendar(prevDate.get(Calendar.YEAR) + 1, prevDate.get(Calendar.MONTH),
                prevDate.get(Calendar.DATE));
        double daysPerYear = 365.0;
        if (DateUtil.hasLeapDayInBetween(prevDate, nextDate.getTime()) == true) {
            daysPerYear = 366.0;
        }

        return daysPerYear;
    }

    public static double getDayCountOfYear(Date callDay) {
        Date matDay = callDay;
        Date preDay = DateUtil.getDateAfter(matDay, Calendar.YEAR, -1);

        GregorianCalendar prevDate = new GregorianCalendar();
        prevDate.setTime(preDay);
        if (prevDate.get(Calendar.MONTH) == Calendar.FEBRUARY && prevDate.get(Calendar.DATE) == 29) {
            return 365.0; // date is 2/29
        }

        if (DateUtil.hasLeapDayInBetween(preDay, matDay) == true) {
            return 366.0;
        }

        return 365.0;
    }

    /**
     * 根据给定日期得到该日所在月的天期
     *
     * @param callDay
     * @return
     */
    public static double getDayCountOfMonth(Date callDay) {
        GregorianCalendar date = new GregorianCalendar();
        date.setTime(callDay);

        return date.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static void main(String[] args) {
        Date date = DateUtil.getDate("2009-02-28");
        Date date2 = DateUtil.getDateAfter(date, Calendar.YEAR, -1);
        System.err.println(isLastDayOfMonth(date));
        System.err.println(isLastDayOfMonth(date2));
        System.err.println(setLastDayOfMonth(date));
        System.err.println(setLastDayOfMonth(date2));
    }

    /**
     * 判断给定的日期是否是该月最后一天
     *
     * @param date
     * @return
     */
    public static boolean isLastDayOfMonth(Date date) {

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);

        if (cal.get(Calendar.DAY_OF_MONTH) == cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
            return true;
        }

        return false;
    }

    /**
     * 改变给定的日程为该月的最后一天
     *
     * @param date
     * @return
     */
    public static Date setLastDayOfMonth(Date date) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);

        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        return cal.getTime();
    }

    /**
     * 2.29日不计息情况下两天之间相隔天数
     * 间有2.29的情况下会比实际天数小一天
     *
     * @param preDate
     * @param nextDate
     * @return
     */
    public static int getDaysBetweenWithoutLeapYear(Date preDate, Date nextDate) {
        int days = DateUtil.getDaysBetween(preDate, nextDate);
        if (DateUtil.hasLeapDayInBetween(preDate, nextDate)) {
            days--;
        }

        return days;
    }

    /**
     * 设置小时分钟秒数到传入的日期中
     * 传入的int数组格式为int[] hms = {HH,mm,ss}
     * 如果数组不符合规则,返回null
     * 如果date为空返回null
     *
     * @param date
     * @param hms
     * @return
     */
    public static Date copyHMS(Date date, int[] hms) {
        if (date == null) {
            return null;
        }
        if (hms == null) {
            return null;
        }
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.set(Calendar.HOUR_OF_DAY, hms[0]);
            c.set(Calendar.MINUTE, hms[1]);
            c.set(Calendar.SECOND, hms[2]);
            return c.getTime();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断给定的时间，是否符合HH:mm:ss
     */
    public static String isTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setLenient(false);
        try {
            sdf.parse(time);
        } catch (ParseException e) {
            return null;
        }
        return time;
    }

    public static Date getDateTime(Date date, String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        sdf.setLenient(false);
        try {
            return sdf.parse(DateUtil.getDateString(date, DateUtil.ymdFormat) + " " + time);
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 是否大于系统规定的最早输入日期1997/01/01
     *
     * @param date
     * @return
     */
    public static boolean isBeforeSysFirstDate(Date date) {
        if (date.before(DateUtil.getDate("1997-01-01"))) {
            return true;
        } else {
            return false;
        }
    }

    /**
	 * 得到日期列表中最早的日期
	 * 列表中不能有null值
	 * @param list
	 * @return
	 */
	public static Date getFirstDate(List<Date> list){
		if(list.size() == 0){
			return null;
		}
		return Collections.min(list);
	}  
    
    public static boolean isBetween(Date CompareDate , Date date1 , Date date2)
    {
        if (date2.before(date1))
        {
            Date tmp = date1;
            date1 = date2;
            date2 = tmp;
        }
        if (CompareDate.before(date1) || CompareDate.after(date2))
            return false;
        return true;
    }

    public static boolean isBetweenNotEqual(Date CompareDate , Date date1 , Date date2)
    {
        if (date2.before(date1))
        {
            Date tmp = date1;
            date1 = date2;
            date2 = tmp;
        }
        if (!CompareDate.after(date1) || !CompareDate.before(date2))
            return false;

        return true;
    }
    /**
    * Function Name               changeNumberToChar                              
    * @param                      month
    * @return                     String
    * @description                将数字月份转换中文月份  			             
     */
    public static String changeNumberToChar(String month){
    	List<String> MONTH_LIST=Arrays.asList("1月份","2月份","3月份","4月份","5月份","6月份","7月份","8月份","9月份","10月份","11月份","12月份");
    	return MONTH_LIST.get(Integer.parseInt(month)-1);
    }


	/**
	 * Function Name calendarMinus
	 * 
	 * @param d1
	 *            //起始日期
	 * @param d2
	 *            //终止日期
	 * @return long
	 * @description //起始日期- 终止日期 =日期相差天数 Modification History //伍冲 2013-03-25
	 *              created
	 */

	public static long calendarMinus(Calendar d1, Calendar d2) {
		if (d1 == null || d2 == null) {
			return 0;
		}
		return (d1.getTimeInMillis() - d2.getTimeInMillis()) / (3600 * 24000);
	}

	/**
	 * String型转为long类型
	 * 
	 * @return long
	 */
	public static long stringTolong(String str) {
		long l = 0;
		try {
			l = Long.parseLong(str);
		} catch (Exception e) {

		}
		return l;
	}

	/**
	 * String转为double类型
	 * 
	 * @return double
	 */
	public static double stringTodouble(String str) {
		double d = 0.00;
		try {
			d = Double.parseDouble(str);
		} catch (Exception e) {

		}
		return d;
	}

	// ----------------------日期、时间相关转化函数--------------------------

	/**
	 * 将 String型 转到 java.sql.Date 格式
	 * 
	 * @param String
	 *            格式表示的日期
	 * 
	 * @return java.sql.Date 格式表示的日期
	 */
	public static Date stringToDate(String str) {
		DateFormat df = null;
		if (str == null || str.trim().length() == 0)
			return null;
		try {
			df = new SimpleDateFormat("yyyy-MM-dd");
			return df.parse(str);
		} catch (ParseException aioe) {
			return null;
		}
	}

	/**
	 * 将String类型转为Calendar类型
	 * 
	 * @return Calendar
	 */
	public static Calendar stringToCalendar(String str) {
		Date date = stringToDate(str);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal;
	}

	/**
	 * 将String类型转为Timestamp类型 param String("yyyy-MM-dd HH:mm:ss" 格式)
	 * 
	 * @return Timestamp
	 */
	public static Timestamp stringToTimestamp(String str) {
		Timestamp sdate = null;
		if (str != null) {
			try {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dt = df.parse(str);
				Calendar cal = Calendar.getInstance();
				cal.setTime(dt);
				return new Timestamp(cal.getTimeInMillis());
			} catch (Exception e) {
			}
		}
		return sdate;
	}

	/**
	 * 将日期格式从 java.util.Calendar 转到 java.sql.Timestamp 格式
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return java.sql.Timestamp 格式表示的日期
	 */
	public static Timestamp calendarToTimestamp(Calendar cal) {
		if (cal == null)
			return null;
		else
			return new Timestamp(cal.getTimeInMillis());
	}

	/**
	 * 将Calendar转为String类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return String("yyyy-MM-dd" 格式)
	 */
	public static String calendarToString(Calendar cal) {
		String sdate = "";
		if (cal != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			sdate = df.format(cal.getTime());
		}
		return sdate;
	}

	/**
	 * 将Calendar转为Date类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return Date
	 */
	public static Date calendarToDate(Calendar cal) {
		return stringToDate(calendarToString(cal));
	}

	/**
	 * 将Date转为String类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return String("yyyy-MM-dd" 格式)
	 */
	public static String dateToString(Date dt) {
		String sdate = "";
		if (dt != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			sdate = df.format(dt);
		}
		return sdate;
	}

	/**
	 * 将Date转为String类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return String("yyyy-MM-dd" 格式)
	 */
	public static String dateToString(Date dt, String dateSplit) {
		String sdate = "";
		if (dt != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy" + dateSplit
					+ "MM" + dateSplit + "dd");
			sdate = df.format(dt);
		}
		return sdate;
	}

	/**
	 * 将Date转为Calendar类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return Calendar
	 */
	public static Calendar dateToCalendar(Date dt) {
		return stringToCalendar(dateToString(dt));
	}

	/**
	 * 将Date转为Timestamp类型
	 * 
	 * @param date
	 *            java.util.Calendar 格式表示的日期
	 * 
	 * @return Timestamp
	 */
	public static Timestamp dateToTimestamp(Date dt) {
		return stringToTimestamp(dateToString(dt));
	}

	/**
	 * timestamp转为Calendar类型 默认使用 yyyy-MM-dd HH:mm:ss 格式
	 * 
	 * @return Calendar
	 */
	public static Calendar timestampToCalendar(Timestamp timestamp) {

		return stringToCalendar(timestampToString(timestamp));
	}

	/**
	 * timestamp转为Date类型 默认使用 yyyy-MM-dd HH:mm:ss 格式
	 * 
	 * @return Date
	 */
	public static Date timestampToDate(Timestamp timestamp) {

		return stringToDate(timestampToString(timestamp));
	}

	/**
	 * timestamp转为String类型 默认使用 yyyy-MM-dd HH:mm:ss 格式
	 * 
	 * @return String("yyyy-MM-dd HH:mm:ss" 格式)
	 */
	public static String timestampToString(Timestamp timestamp) {
		String rettime = "";
		if (timestamp != null) {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			rettime = formatter.format(timestamp);
		}
		return rettime;
	}

	/**
	 * 取得系统当前时间
	 * 
	 * @return String yyyy-mm-dd hh:MM:ss
	 */
	public static String getCurrentDateTime() {
		Calendar rightNow = Calendar.getInstance();
		return timestampToString(calendarToTimestamp(rightNow));
	}

	/**
	 * 取得系统当前时间
	 * 
	 * @return String yyyy-mm-dd hh:MM:ss
	 */
	public static String getCurrentDateTime(String DateTimeStyle) {
		Calendar rightNow = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(DateTimeStyle);
		return formatter.format(rightNow.getTime());
	}

	/**
	 * 取得系统当前时间
	 * 
	 * @return String yyyy-mm-dd
	 */
	public static String getCurrentDate() {
		Calendar rightNow = Calendar.getInstance();
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH) + 1;
		int day = rightNow.get(Calendar.DATE);
		return year + "-" + month + "-" + day;
	}

	/**
	 * 获取指定年月的最后一天
	 * 
	 * @param 传入
	 *            "yyyy-mm"的年月格式
	 * 
	 *            比如 获得2007年4月份的最大日期：getMaxDate("2007-04"); = "2007-04-30"
	 * @return 输出某年月的最后一天的日期
	 */

	public static Calendar getMaxDate(String str) {
		Calendar cal = null;
		if (str == null || str.trim().length() == 0)
			return null;
		String dateStr = str + "-01";
		cal = stringToCalendar(dateStr);
		int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, maxDay);
		return cal;
	}

	/**
	 * 根据传入的String格式日期（yyyy-mm-dd），和 数字型天数（可为负值），计算天数
	 * 
	 * 比如计算"2007-4-30"的前5天 calendarCaculate("2007-4-30",-5)；
	 * 
	 * 比如计算"2007-4-30"的后5天 calendarCaculate("2007-4-30",5)；
	 * 
	 * @param 传入
	 *            "yyyy-mm"的年月格式
	 * 
	 * @param 传入
	 *            int型计算天数
	 * 
	 * @return 输出计算后日期
	 */
	public static Calendar calendarCaculate(String strdate, int num) {
		Calendar cal = stringToCalendar(strdate);
		cal.add(Calendar.DAY_OF_MONTH, num);
		return cal;
	}

	/**
	 * 根据传入的Calendar类型，和 数字型天数（可为负值），计算天数
	 * 
	 * 比如计算"2007-4-30"的前5天 calendarCaculate(calendar,-5)；
	 * 
	 * 比如计算"2007-4-30"的后5天 calendarCaculate(calendar,5)；
	 * 
	 * @param 传入
	 *            "yyyy-mm"的年月格式
	 * 
	 * @param 传入
	 *            int型计算天数
	 * 
	 * @return 输出计算后日期
	 */
	public static Calendar calendarCaculate(Calendar calendar, int num) {
		calendar.add(Calendar.DAY_OF_MONTH, num);
		return calendar;
	}

	/**
	 * 根据传入的String类型 如：2007-01-01 ,2007-12-31,计算他们之间年月，返回包含年月的list
	 * 比如计算2007-01-01 ,2007-12-31之间相差的月份
	 * 
	 * caculateDateNum("2007-01-01","2007-12-31")；返回 list
	 * 包含了{200701、200702、200703
	 * 、200704、200705、200706、200707、200701、200709、200710、200711、200712}
	 * 
	 * @param 传入
	 *            "yyyy-mm-dd"的年月日格式
	 * @param 传入
	 *            "yyyy-mm-dd"的年月日格式
	 * @return 输出返回包含年月为'yyyymm'格式的list
	 */
	public static ArrayList caculateDateNum(String startDate, String endDate) {
		ArrayList loop = new ArrayList();

		// 获取查询年份
		String startYear = startDate.substring(0, 4);
		String endYear = endDate.substring(0, 4);
		// 获取查询月份
		String startMonth = startDate.substring(5, 7);
		String endMonth = endDate.substring(5, 7);
		// 计算月份数量,放入数组中

		if (Long.parseLong(startYear) == Long.parseLong(endYear)) {
			long loopmonth = Long.parseLong(endMonth)
					- Long.parseLong(startMonth);
			for (int i = 0; i <= loopmonth; i++) {
				long tempmonth = Long.parseLong(startMonth) + i;
				if (tempmonth < 10) {
					loop.add(startYear + "0" + tempmonth);
				} else {
					loop.add(startYear + tempmonth);
				}
			}
		}

		if (Long.parseLong(startYear) < Long.parseLong(endYear)) {
			final int maxMonth = 12;
			final int minMonth = 1;
			long loopyear = Long.parseLong(endYear) - Long.parseLong(startYear);
			for (int i = 0; i <= loopyear; i++) {
				String tempYear = String.valueOf(Long.parseLong(startYear) + i);
				if (tempYear.equals(startYear)) {
					long loopmonth = maxMonth - Long.parseLong(startMonth);
					for (int j = 0; j <= loopmonth; j++) {
						long tempmonth = Long.parseLong(startMonth) + j;
						if (tempmonth < 10) {
							loop.add(tempYear + "0" + tempmonth);
						} else {
							loop.add(tempYear + tempmonth);
						}
					}
				} else if (tempYear.equals(endYear)) {
					long loopmonth = Long.parseLong(endMonth);
					for (int j = minMonth; j <= loopmonth; j++) {
						long tempmonth = j;
						if (tempmonth < 10) {
							loop.add(tempYear + "0" + tempmonth);
						} else {
							loop.add(tempYear + tempmonth);
						}
					}
				} else {
					for (int j = minMonth; j <= maxMonth; j++) {
						long tempmonth = j;
						if (tempmonth < 10) {
							loop.add(tempYear + "0" + tempmonth);
						} else {
							loop.add(tempYear + tempmonth);
						}
					}
				}
			}
		}
		return loop;
	}

	public static String getDateString2(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat myformat = new SimpleDateFormat(SHORTDATE);
		String datetime = myformat.format(date);
		return datetime;
	}

	public static String getCurrentYear() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(new Date());
	}

	public static String getYear(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(date);
	}

	public static Integer getAge(Date birthday) {
		if (birthday == null) {
			return 0;
		}
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(SHORT_DATE);
			String cTime = sdf.format(new Date());
			int cYear = Integer.valueOf(cTime.substring(0, 4));
			int cMonth = Integer.valueOf(cTime.substring(5, 7));
			int cDay = Integer.valueOf(cTime.substring(8, 10));

			String bTime = sdf.format(birthday);
			int bYear = Integer.valueOf(bTime.substring(0, 4));
			int bMonth = Integer.valueOf(bTime.substring(5, 7));
			int bDay = Integer.valueOf(bTime.substring(8, 10));

			int year = cYear - bYear;
			if (cMonth > bMonth || (cMonth == bMonth && cDay >= bDay)) {
				year += 1;
			}
			return year;
		} catch (Exception e) {
			return 0;
		}
	}

	public static String getCurrentMonth() {
		SimpleDateFormat sdf = new SimpleDateFormat("MM");
		return sdf.format(new Date());
	}

	public static Date convert2Date(String dateString) {
		if (StringUtils.isNotBlank(dateString)) {
			SimpleDateFormat sFormat = new SimpleDateFormat(SHORT_DATE);
			try {
				return sFormat.parse(dateString);
			} catch (ParseException e) {
				try {
					return sFormat.parse(LONG_DATE);
				} catch (ParseException e1) {
					try {
						return sFormat.parse(TIME);
					} catch (ParseException e2) {
						// logger.error("Convert time is error! The dateString is "
						// + dateString + "." +
						// Exceptions.getStackTraceAsString(e2));
					}
				}
			}
		}
		return null;
	}

	public static Date convert3Date(String dateString) {
		if (StringUtils.isNotBlank(dateString)) {
			SimpleDateFormat sFormat = new SimpleDateFormat(LONG_DATE);
			try {
				return sFormat.parse(dateString);
			} catch (ParseException e) {
				try {
					return sFormat.parse(LONG_DATE);
				} catch (ParseException e1) {
					try {
						return sFormat.parse(TIME);
					} catch (ParseException e2) {
						// logger.error("Convert time is error! The dateString is "
						// + dateString + "." +
						// Exceptions.getStackTraceAsString(e2));
					}
				}
			}
		}
		return null;
	}

	/**
	 * 
	 * 
	 * <p>
	 * Title: longToStr
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param mill
	 * @return
	 */
	public static final String longToStr(long mill) {
		SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return SDF.format(new Date(mill));
	}

	/**
	 * 
	 * 
	 * <p>
	 * Title: formatDateTime
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDateTime(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat myformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = myformat.format(date);
		return datetime;
	}

	public static String formatDateStrEn(Date date,String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US); 
		try {
			return sdf.format(date); 
		} catch (Exception e) {
			System.err.println("Exception caught: " + e.getMessage());
		}
		return null;
	}
	
	public static String formatDateStr(Date date,String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
		try {
			return sdf.format(date); 
		} catch (Exception e) {
			System.err.println("Exception caught: " + e.getMessage());
		}
		return null;
	}
	
	public static String formatDateTime2(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat myformat = new SimpleDateFormat(LONGDATE);
		String datetime = myformat.format(date);
		return datetime;
	}

	/**
	 * 
	 * 
	 * <p>
	 * Title: createKey
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @return
	 */
	public static String createKey() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 
	 * 
	 * <p>
	 * Title: getCurrentTime
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @return
	 */
	public static String getCurrentTime() {
		java.util.Date date = new java.util.Date();
		// 日期格式 2010-12-8 15:32:58
		String currTime = DateFormat.getDateTimeInstance().format(date);
		return currTime;
	}

	/**
	 * 获取指定时间的周一
	 * 
	 * @param todayCalendar
	 * @return
	 */
	public static Date getMonday(Calendar todayCalendar) {
		Calendar mondayCalendar = Calendar.getInstance();
		// 如果是周日
		if (todayCalendar.get(Calendar.DAY_OF_WEEK) == 1) {
			mondayCalendar.add(Calendar.DATE, -6);
			// 如果是周一
		} else if (todayCalendar.get(Calendar.DAY_OF_WEEK) == 2) {
		} else {
			mondayCalendar.add(Calendar.DATE,
					2 - todayCalendar.get(Calendar.DAY_OF_WEEK));
		}
		try {
			String dateStr = new SimpleDateFormat("yyyy-MM-dd")
					.format(mondayCalendar.getTime());
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 获取指定时间的周日
	 * 
	 * @param todayCalendar
	 * @return
	 */
	public static Date getSunday(Calendar todayCalendar) {
		Calendar sundayCalendar = Calendar.getInstance();
		// 如果是周日
		if (todayCalendar.get(Calendar.DAY_OF_WEEK) == 1) {
			// 如果是周一
		} else if (todayCalendar.get(Calendar.DAY_OF_WEEK) == 2) {
			sundayCalendar.add(Calendar.DATE, 6);

		} else {
			sundayCalendar.add(Calendar.DATE,
					8 - todayCalendar.get(Calendar.DAY_OF_WEEK));
		}
		try {
			String dateStr = new SimpleDateFormat("yyyy-MM-dd")
					.format(sundayCalendar.getTime()) + " 23:59:59";
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
		} catch (ParseException e) {
			return null;
		}
	}
	
}